<template>
	<div>
		<!-- 面包屑导航区域 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
		  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		
		<!-- 卡片视图区域 -->
		<el-card>
			<!-- 搜索与添加区域 -->
			<el-row :gutter="20">
				<el-col :span="7">
					<el-input placeholder="请输入内容" v-model="page.keyword" clearable @clear="getList()">
						<el-button slot="append" icon="el-icon-search" @click="getList()"></el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="addDialog()">添加用户</el-button>
				</el-col>
			</el-row>
			<!-- 用户列表区域 -->
			<el-table :data="userList" :cell-style="{ textAlign: 'center' }" :header-cell-style="{textAlign: 'center'}"  border>
				<el-table-column width="50px" label="编号" type="index"></el-table-column>
				<el-table-column label="用户名" prop="name"></el-table-column>
				<el-table-column label="昵称" prop="nickname"></el-table-column>
				<el-table-column label="头像" >
					<template slot-scope="scope">
						<img :src="scope.row.avatar" min-width="70" height="70" />
					</template>
				</el-table-column>
				<el-table-column  label="电话" prop="phone"></el-table-column>
				<el-table-column label="角色">
					<template slot-scope="scope">
						{{delLevel(scope.row.level)}}
					</template>
				</el-table-column>
				<el-table-column label="状态" prop=""></el-table-column>
				<el-table-column label="操作" >
					<template slot-scope="scope">
						<!-- 修改按钮 -->
						<el-button @click="showEditDialog(scope.row)" type="primary" icon="el-icon-edit" circle></el-button>
						<!-- 删除按钮 -->
						<el-button type="danger" icon="el-icon-delete" @click="removeUser(scope.row.id)" circle></el-button>
						<!-- 分配角色按钮 -->
						<el-tooltip effect="dark" content="分配角色" :enterable="false" placement="top">
						      <el-button type="warning" icon="el-icon-s-tools" circle></el-button>
						</el-tooltip>
						
					</template>
				</el-table-column>
			</el-table>
			<!-- 添加分页功能 -->
				<el-pagination
					  @size-change="handleSizeChange"
					  @current-change="handleCurrentChange"
					  :current-page="page.current"
					  :page-sizes="[1, 2, 5, 10]"
					  :page-size="page.size"
					  layout="total, sizes, prev, pager, next, jumper"
					  :total="page.total">
				</el-pagination>
		</el-card>
		
		<!-- 添加用户的对话框 -->
		<el-dialog
		  :title="operateType"
		  :visible.sync="addDialogVisible"
		  width="50%"
		  @close="addDialogClosed">
		  <!-- 内容主题区域 -->
		  
		  <el-form :rules="FormRules" ref="addFormRef" :model="addForm" label-width="80px">
		    <el-form-item label="用户名" prop="account" >
		      <el-input v-model="addForm.account" :disabled="this.isEdit"></el-input>
		    </el-form-item>
			<el-form-item label="昵称" prop="nickname" >
			  <el-input v-model="addForm.nickname"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
			  <el-input v-model="addForm.password"></el-input>
			</el-form-item>
			<el-form-item label="手机号" prop="phone">
			  <el-input v-model="addForm.phone"></el-input>
			</el-form-item>
			<el-form-item label="头像">
				<!-- 上传头像 -->
			  <!-- <el-input v-model="addForm.avatar"></el-input> -->
			  <el-upload
			    class="avatar-uploader"
			    action="http://uat.ynzxsc.com/mallrest/imgs/upload"
				name="picture"
			    :show-file-list="false"
			    :on-success="handleAvatarSuccess"
			    :before-upload="beforeAvatarUpload">
			    <img v-if="this.addForm.avatar" :src="this.addForm.avatar" class="avatar">
			    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
			  </el-upload>
			</el-form-item>
			
		  </el-form>
		  
		  <!-- 底部区域 -->
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="addUserList">确 定</el-button>
		  </span>
		</el-dialog>
		
		
	</div>
</template>

<script>
	import { getUser, addUser, deleteUser,editUser } from '../../common/api/data.js';
	export default{
		data(){
			
			// 验证手机的规则
			var checkMobile = (rule,value,cb) => {
				// 验证手机号的正则
				const regMobile = /^1[3456789]\d{9}$/
				
				if(regMobile.test(value)){
					// 合法的手机号
					return cb()
				}
				cb(new Error('请输入合法的手机号'))
			}
			return{	
				
				// operateType : add,
				isEdit:false,
				// 获取用户列表的参数对象
				
				page : {
					total : 0,
					totalPage : 0,
					// 当前的页数
					current:1,
					// 当前每页显示多少条数据
					size:10,
					// 查询参数,可为空
					keyword:'',
				},
				total:0,
				userList:[
						// {
						// 	mobile: '18190727612',
						// 	// num : '1',
						// 	username: '王小虎',
						// 	pic: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fb291684fb036503c58bcc0e60215ee70b5fc416c387e-vPj3Ut_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652618547&t=4b67db119ba00143b6ceec2f80dabaae',
						// 	role_name : '超级管理员'
						//   }, 
						//   {
						//   	mobile: '13888888888',
						// 	// num : '2',
						//   	username: '小李子',
						//   	pic: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx2.sinaimg.cn%2Fthumb150%2Fe72082c6gy1fkhnm3qajcj20j60sr74p.jpg&refer=http%3A%2F%2Fwx2.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652618547&t=18184e8d7195ab3976e2554a5e62a185',
						//   	role_name : '测试账号'
						//     },
					
					],
					
					// 控制对话框的隐藏,添加用户与修改用户
					addDialogVisible:false,
					// editDialogVisible:false,
					// 添加用户的表单数据
					addForm:{
						account:'',
						nickname:'',
						password:'',
						phone:'',
						avatar:'',
						
					},
					
					// 添加表单的验证规则对象
					FormRules:{
						// 验证用户名是否合法
						account:[
							{ required: true, message: '请输入用户名', trigger: 'blur' },
							{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
						],
						// 验证密码是否合法
						password:[
							{ required: true, message: '请输入密码', trigger: 'blur' },
							{ min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
						],
						// 验证手机是否合法
						phone:[
							{ required: true, message: '请输入密码', trigger: 'blur' },
							{validator:checkMobile, trigger: 'blur' }
						],
						nickname:[
							{required: true,message: '请输入昵称', trigger: 'blur'},
							{ min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
						]
						
					}
			}
		},
		computed:{
			operateType(){
				if(this.isEdit){
					return '编辑用户'
				}else{
					return '新增用户'
				}
			}
		},
		created(){
			this.getList()
		},
		methods:{
			// 上传图片
			 handleAvatarSuccess(res, file) {
			        // this.this.addForm.avatar = URL.createObjectURL(file.raw);
					if(res.code == 0){
						this.addForm.avatar = res.data
					}else{
						this.$message.error('上传失败')
					}
			      },
			      beforeAvatarUpload(file) {
			        const isJPG = file.type === 'image/jpeg';
			        const isLt2M = file.size / 1024 / 1024 < 2;
			
			        if (!isJPG) {
			          this.$message.error('上传头像图片只能是 JPG 格式!');
			        }
			        if (!isLt2M) {
			          this.$message.error('上传头像图片大小不能超过 2MB!');
			        }
			        return isJPG && isLt2M;
			      },
			
			// 获取表单中所有的用户信息
			getList() {
				getUser(this.page).then((res) => {
					// console.log(res)
					if(res.code !== 0){
						return this.$message.error('获取用户信息失败')
					}else{
						this.userList = res.data.data
						// this.total = res.data.count
						this.page.total = res.data.count
						this.page.totalPage = res.data.pages
						// this.page.pagenum = res.data.current,
						// this.page.size = res.data.size
					}
				})
			},
			// 鉴于不同的level值给予不同的用户权限
			delLevel(level){
				if(level == 1){
					return '超级管理员'
				}else if(level == 2){
					return '普通用户'
				}
			},
			// 添加用户的操作
			addUserList(){
				this.$refs.addFormRef.validate(vaild => {
					// 验证表单合法性,是否为空
					if(!vaild) return;
					if (this.isEdit) {
						editUser(this.addForm).then((res) => {
							if(res.code !== 0){
								return this.$message.error(res.message)
							}else{
								this.addDialogVisible = false,
								this.getList()
							}
						})
					} else {
						addUser(this.addForm).then((res) => {
							if(res.code !== 0){
								return this.$message.error(res.message)
							}else{
								this.addDialogVisible = false,
								this.getList()
							}
						})
					}
					
					
					
				})
			},
			// 更改用户信息
			editUserList(){
				this.$refs.editFormRef.validate(vaild => {
					// 验证表单合法性,是否为空
					if(!vaild) return;
					editUser(this.editForm).then((res) => {
						if(res.code !== 0){
							return this.$message.error(res.message)
						}else{
							this.eidtDialogVisible = false,
							this.getList(),
							this.$message.success("修改用户成功")
						}
					})
				})
			},
			// 监听size值的改变
			handleSizeChange(newSize){
				this.page.size = newSize
				this.page.current = 1 
				this.getList()
			},
			// 监听页码值的改变
			handleCurrentChange(newPage){
				this.page.current = newPage,
				this.getList()
			},
			resetForm(){
				this.addForm = {
						account:'',
						password:'',
						phone:'',
						avatar:'',
						
					}
			},
			// 监听添加用户对话框的关闭事件
			addDialogClosed(){
				// this.$refs.addFormRef.resetFields()
				this.resetForm()
			},
			addDialog(){
				this.addDialogVisible = true
				this.isEdit = false
			},
			// 监听关闭对话框的关闭事件
			editDialogClosed(){
				// this.$refs.addFormRef.resetFields()
				this.resetForm()
				
			},
			// 展示编辑用户的对话框
			showEditDialog(user){
				 this.isEdit = true
				// console.log(user)
				this.addForm.avatar = user.avatar
				this.addForm.account = user.account
				this.addForm.phone = user.phone
				this.addForm.password = user.password
				this.addDialogVisible = true
			},
			// 根据id删除用户
			removeUser(userId){
				// 询问是否确定删除
				// console.log(id)
				this.$confirm("此操作将永久删除该用户，是否继续？","提示",{
					confirmButtonText:"确认",
					cancelButtonText:"取消",
					type:"warning"
				}).then(()=>{
					// 调用删除接口
					// console.log(userId)
					deleteUser({userId}).then((res)=>{
						if(res.code !== 0){
							this.$message(res.message)
						}else{
							this.$message({
								type:'success',
								message:'删除用户成功'
							})
							this.getList()
						}	
					})
				}).catch(() => {
					this.$message({
						type:'info',
						message:'取消删除成功'
					})
				})
			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	el-table{
		align-items: center;
	}
	el-pagination{
		margin-top: 15px;
	}
	/deep/.avatar-uploader .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    position: relative;
	    overflow: hidden;
	  }
	 /deep/ .avatar-uploader .el-upload:hover {
	    border-color: #409EFF;
	  }
	  .avatar-uploader-icon {
	    font-size: 28px;
	    color: #8c939d;
	    width: 178px;
	    height: 178px;
	    line-height: 178px;
	    text-align: center;
	  }
	  .avatar {
	    width: 178px;
	    height: 178px;
	    display: block;
	  }
</style>
